package com.example.ai.controller;

import com.example.ai.dto.UserProfileDTO;
import com.example.ai.dto.auth.AuthResponse;
import com.example.ai.dto.auth.LoginRequest;
import com.example.ai.dto.auth.LoginResponse;
import com.example.ai.dto.auth.RegisterRequest;
import com.example.ai.service.AuthService;
import com.example.ai.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.ai.security.JwtService;
import com.example.ai.dto.MessageResponse;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final AuthenticationManager authenticationManager;
    private final JwtService jwtService;
    private final UserService userService;

    @PostMapping("/register")
    public ResponseEntity<AuthResponse> register(
            @Valid @RequestBody RegisterRequest request
    ) {
        return ResponseEntity.ok(authService.register(request));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        log.info("Received login request for user: {}", loginRequest.getUsername());
        
        try {
            log.debug("Attempting authentication...");
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    loginRequest.getUsername(),
                    loginRequest.getPassword()
                )
            );
            log.debug("Authentication successful");

            String jwt = jwtService.generateToken(authentication);
            log.debug("JWT token generated");

            UserProfileDTO userProfile = userService.getUserProfile(loginRequest.getUsername());
            LoginResponse response = new LoginResponse(jwt, loginRequest.getUsername(),userProfile.getAvatar());
            log.info("Login successful for user: {}", loginRequest.getUsername());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Login failed for user: {}", loginRequest.getUsername(), e);
            return ResponseEntity
                .status(HttpStatus.UNAUTHORIZED)
                .body(new MessageResponse("Invalid username or password: " + e.getMessage()));
        }
    }
} 